package com.ccn.qrcode.controller;

import cn.hutool.core.bean.BeanUtil;
import com.ccn.qrcode.common.Constant;
import com.ccn.qrcode.pojo.QrcodeFilePojo;
import com.ccn.qrcode.service.QrcodeFileService;
import com.ccn.qrcode.utils.QrcodeUtils;
import com.ccn.qrcode.utils.json.JSONBeanUtils;
import com.ccn.qrcode.utils.qrcodefile.QrcodeFileUtils;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 二维码生成入口
 * @author tig
 */
@RestController
@RequestMapping("/qrcode")
public class QrcodeController {

    private static final Logger logger = LoggerFactory.getLogger(QrcodeController.class);


    @Autowired
    private QrcodeFileService qrcodeFileService;

    /**
     * 二维码文件生成
     * @return
     */
    @RequestMapping("/qrCodeGenerate")
    public List<String> qrCodeGenerate(@RequestParam("file") MultipartFile file) throws Exception {
        List<String> generatedQrcodePaths = Lists.newArrayList();
        //拿到文件
        List<QrcodeFilePojo> fileTxtList = qrcodeFileService.fileAnalysis(file);
        //先清空临时文件夹
        //文件逐一解析, 后面有时间在做优化
        for (int i = 0; i < fileTxtList.size(); i++) {
            QrcodeFilePojo filePojo = fileTxtList.get(i);
            // 图片尺寸
            String filePath = Constant.FILE_TMP_PATH+filePojo.getFileName()+"."+Constant.FORMAT;
            qrcodeFileService.createQrcode(filePojo, filePath);
            //jpg直接转成tiff。没特殊处理
            generatedQrcodePaths.add(JSONBeanUtils.objectToJson(filePojo));
            logger.info("文件{},生成成功", filePath);
        }
        return generatedQrcodePaths;
    }


    /**
     * 图片解析，查看防伪码正确率
     */
    @RequestMapping("/qrCodeAnalysis")
    public String  qrCodeAnalysis(@RequestParam("file") MultipartFile multipartFile) throws Exception{
        File file = QrcodeFileUtils.transferToFile(multipartFile);
        return QrcodeUtils.decodeQrcode(file);
    }



}














